package com.weapons.week0903_weapons.fragment;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.weapons.week0903_weapons.R;
import com.weapons.week0903_weapons.activity.ImageShowActivity;
import com.weapons.week0903_weapons.adapter.ImageRecycleAdapter;
import com.weapons.week0903_weapons.bean.ImageBean;
import com.weapons.week0903_weapons.constant.UrlString;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class ImageFragment extends Fragment {
    private Activity mActivity;
    private String mpos="";
    private SwipeRefreshLayout srfreshLayout;
    private RecyclerView recyclerView;
    private List<ImageBean.ItemBean> mDatas;
    private OkHttpClient mClient;
    private int maxPage;
    private int currentPage = 1;
    private ImageRecycleAdapter mAdapter;
    private GridLayoutManager manager;
    private int lastVisibleItem;

    public ImageFragment newInstance(String pos) {
        ImageFragment fragment=new ImageFragment();
        Bundle bundle=new Bundle();
        bundle.putString("pos",pos);
        fragment.setArguments(new Bundle(bundle));
        return fragment;
    }
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity=getActivity();
        Bundle bundle=getArguments();
        if (bundle!=null){
            mpos=bundle.getString("pos");
        }
        mDatas = new ArrayList<>();
        mAdapter = new ImageRecycleAdapter(mDatas,getContext());
        initData(String.format(UrlString.URL_IMAGE,currentPage));
    }
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_image,container,false);
        srfreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.image_swiperefresh);
        recyclerView = (RecyclerView) view.findViewById(R.id.image_recycleview);
        return view;
    }
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //刷新的小圆圈的颜色：可以传入多个色值，依次改变颜色
        srfreshLayout.setColorSchemeColors(Color.BLUE, Color.YELLOW, Color.DKGRAY);
        //设置刷新按钮的背景颜色
        srfreshLayout.setProgressBackgroundColorSchemeColor(Color.GREEN);
        // 这句话是为了，第一次进入页面的时候显示加载进度条
        srfreshLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        srfreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            public void onRefresh() {
                mDatas.clear();
                currentPage = 1;
                initData(String.format(UrlString.URL_IMAGE,currentPage));
            }
        });
        mAdapter.setOnItemClickListener(new ImageRecycleAdapter.OnRecyclerViewItemClickListenner() {
            public void onItemClick(View view, String uriId) {
                Intent intent = new Intent(getActivity(), ImageShowActivity.class);
                intent.putExtra("image",uriId);
                TextView tv = (TextView) view.findViewById(R.id.itemImage_tv);
                intent.putExtra("image1",tv.getText());
                startActivity(intent);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = manager.findLastVisibleItemPosition();
            }
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == mAdapter.getItemCount()){
                    srfreshLayout.setRefreshing(true);
                    if(currentPage <= 9 && currentPage >= 1){
                        initData(String.format(UrlString.URL_IMAGE,++currentPage));
                    }else if(currentPage == 10){
                        currentPage = 1;
                        srfreshLayout.setRefreshing(false);
                    }
                }
            }
        });
    }
    public void initData(String uri) {
        mClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(uri)
                .build();
        mClient.newCall(request).enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {

            }
            public void onResponse(Call call, Response response) throws IOException {
                ImageBean bean = new Gson().fromJson(response.body().string(),ImageBean.class);
                maxPage = bean.getMaxpage();
                mDatas.addAll(bean.getItem());
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        mAdapter.notifyDataSetChanged();
                        recyclerView.setAdapter(mAdapter);
                        srfreshLayout.setRefreshing(false);
                        manager =  new GridLayoutManager(getContext(),2,GridLayoutManager.VERTICAL, false);
                      // LinearLayoutManager manager = new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
                        recyclerView.setLayoutManager(manager);
                        recyclerView.scrollToPosition(mDatas.size()-10);
                    }
                });
            }
        });
    }
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

}
